import Access from '@/components/Access';
import { ProFormInstance, ProFormTextArea, ProFormTreeSelect } from '@/components/Pro';
import type { ActionType, ProColumns } from '@/components/Pro/';
import {
  ModalForm,
  ProFormItem,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@/components/Pro/';
import {
  sysOrgControllerList as getList,
  sysOrgControllerTree,
  sysOrgControllerUserInfo,
} from '@/services/ess/sysOrg';
import { sysRoleControllerList } from '@/services/ess/sysRole';
import {
  sysUserControllerDelete,
  sysUserControllerEdit,
  sysUserControllerResetPassword,
  sysUserControllerSave,
  sysUserControllerSetStatus,
  sysUserControllerThaw,
} from '@/services/ess/sysUser';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import '@umijs/max';
import { useModel } from '@umijs/max';
import { message, Modal, Space, Switch, theme } from 'antd';
import React, { useRef, useState } from 'react';
import { useAccess, useIntl } from 'umi';

const { useToken } = theme;

interface paramType {
  orgId?: string;
}

const TableList: React.FC<paramType> = ({ orgId }) => {
  const [messageApi] = message.useMessage();
  const modalFormRef = useRef<ProFormInstance>();
  const { confirm } = Modal;
  const [modalTitle, setModalTitle] = useState('新增用户');
  const [modalEditFlag, setModalEditFlag] = useState(false);
  const { token } = useToken();
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.SysUser>();
  const { initialState } = useModel('@@initialState') as any;
  const access = useAccess();
  const intl = useIntl();

  const handleLineDel = (record: any) => {
    confirm({
      title: '提示',
      content: '数据删除后将不可恢复，是否删除',
      onOk() {
        //单条删除方法
        sysUserControllerDelete([record.userId]).then((res) => {
          if (res.success) {
            message.success(`删除成功`);
            actionRef?.current?.reloadAndRest?.();
          }
        });
      },
      onCancel() {},
    });
  };

  const columns: ProColumns<API.SysUser>[] = [
    {
      title: '序号',
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
    },
    {
      title: '用户角色',
      dataIndex: 'roleName',
      width: 120,
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
    },
    {
      title: '用户状态',
      dataIndex: 'status',
      fixed: 'right',
      width: 80,
      request: async () => {
        return await fetchDictInfo(DATABASE_TYPE_ENUM.USER_STATUS);
      },
      render: (_: ReactNode, record: API.SysTenant) => {
        return [
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            checked={record.status === 1}
            key="switchVal"
            onChange={(checked) => {
              confirm({
                title: '提示',
                content: '是否变更该条数据的启用状态？',
                onOk: async () => {
                  const res = await sysUserControllerSetStatus({
                    userIds: [record?.userId],
                    action: checked,
                  });
                  if (res?.success) {
                    message.success(`${checked ? '启用' : '禁用'}成功`);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          />,
        ];
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 200,
      render: (_, record) => [
        <Space key="space">
          <Access accessible={access['sys:user:reset']} key="reset">
            <a
              key="reset"
              onClick={async () => {
                confirm({
                  title: intl.formatMessage({
                    id: 'systemManagement.requiredFields.resetPassword',
                  }),
                  content: intl.formatMessage({
                    id: 'systemManagement.requiredFields.confirmResetPassword',
                  }),
                  onOk() {
                    const { userId } = record;
                    sysUserControllerResetPassword({ userId: userId }).then((res) => {
                      if (res.success) {
                        Modal.info({
                          title: intl.formatMessage({
                            id: 'systemManagement.requiredFields.siteNameOrCode',
                          }),
                          content: `最新密码为${res.data}`,
                        });
                      }
                    });
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.requiredFields.resetPassword' })}
            </a>
          </Access>

          <Access accessible={access['sys:user:list']} key="look">
            <a
              key="config"
              onClick={() => {
                setModalTitle(intl.formatMessage({ id: 'systemManagement.generalProcedure.view' }));
                setModalEditFlag(true);
                handleModalOpen(true);
                sysOrgControllerUserInfo({ userId: record.userId }).then((res) => {
                  setCurrentRow(res.data);
                  const visibleStationIds = res.data?.visibleStations.map((res) => res.id) || [];
                  const roleIds = res.data?.roles.map((res) => res.id) || [];
                  modalFormRef?.current?.setFieldsValue({
                    visibleStationIds: visibleStationIds,
                    roleIds: roleIds,
                    ...res.data,
                  });
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.view' })}
            </a>
          </Access>

          <Access accessible={access['sys:user:edit']} key="edit">
            <a
              key="edit"
              onClick={() => {
                setModalTitle(intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' }));
                setModalEditFlag(false);
                handleModalOpen(true);
                sysOrgControllerUserInfo({ userId: record.userId }).then((res) => {
                  setCurrentRow(res.data);
                  const visibleStationIds = res.data?.visibleStations.map((res) => res.id) || [];
                  const roleIds = res.data?.roles.map((res) => res.id) || [];

                  modalFormRef?.current?.setFieldsValue({
                    visibleStationIds: visibleStationIds,
                    roleIds: roleIds,
                    ...res.data,
                  });
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
          </Access>

          {initialState.userId !== record.userId ? (
            <Access accessible={access['sys:user:del']} key="del">
              <a
                key="delete"
                style={{ color: token.colorError }}
                onClick={() => {
                  handleLineDel(record);
                }}
              >
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
              </a>
            </Access>
          ) : (
            <span></span>
          )}
        </Space>,
      ],
    },
  ];

  // 解除冻结
  const handleCancelFreeze = () => {
    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: '是否要取消冻结',
      onOk() {
        sysUserControllerThaw({ userId: currentRow?.userId }).then((res) => {
          if (res.success) {
            messageApi.open({
              type: 'success',
              content: res.message,
            });
            actionRef?.current?.reloadAndRest?.();
          }
        });
      },
    });
  };

  return (
    <div>
      <ProTable<API.OrgQuery, API.PageParams>
        actionRef={actionRef}
        rowKey="userId"
        search={{
          labelWidth: 110,
        }}
        params={{ orgId: orgId }}
        request={async (params) => {
          const result = await getList(params);
          return result;
        }}
        columns={columns}
      />
      <ModalForm
        defaultValue={currentRow}
        formRef={modalFormRef}
        title={modalTitle}
        width="750px"
        colProps={{ md: 12 }}
        disabled={modalEditFlag}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        submitter={!modalEditFlag}
        onFinish={async (value) => {
          if (
            modalTitle !== intl.formatMessage({ id: 'systemManagement.requiredFields.addUser' })
          ) {
            value.userId = currentRow?.userId;
            const res = await sysUserControllerEdit(value);
            if (res.success) {
              message.success('编辑成功');
              handleModalOpen(false);
              actionRef?.current?.reloadAndRest?.();
            }
          } else {
            const res = await sysUserControllerSave(value);
            if (res.success) {
              message.success('新增成功');
              handleModalOpen(false);
              actionRef?.current?.reloadAndRest?.();
            }
          }
        }}
      >
        <ProFormText
          name="userName"
          label={intl.formatMessage({ id: 'systemManagement.systemLogMenu.userAccount' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.userAccount' }),
            },
          ]}
        />
        <ProFormText
          name="nickName"
          label={intl.formatMessage({ id: 'systemManagement.userManagement.userFullName' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.userName' }),
            },
          ]}
        />
        <ProFormText
          name="phone"
          label="手机号码"
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.phoneNumber' }),
            },
          ]}
        />
        <ProFormTreeSelect
          name="orgId"
          label="所属组织"
          fieldProps={{
            fieldNames: {
              label: 'name',
              value: 'id',
              children: 'children',
            },
          }}
          request={async () => {
            const res = await sysOrgControllerTree({ orgName: '' });
            return res.data;
          }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.organization' }),
            },
          ]}
        />
        <ProFormSelect
          name="visibleStationIds"
          label={intl.formatMessage({
            id: 'systemManagement.organizationalManagementMenu.plantPermissions',
          })}
          mode="multiple"
          fieldProps={{
            fieldNames: {
              label: 'stationName',
              value: 'id',
            },
          }}
          request={async () => {
            const tempArray: any[] = [];
            initialState.tenants.forEach((item: any) => {
              tempArray.push(...item.stationInfos);
            });
            return tempArray;
          }}
        />
        <ProFormSelect
          name="roleIds"
          request={async () => {
            const res = await sysRoleControllerList({ search: { roleName: '' }, page: {} });
            return res.data.records;
          }}
          label={intl.formatMessage({
            id: 'systemManagement.organizationalManagementMenu.userRole',
          })}
          fieldProps={{
            fieldNames: {
              label: 'roleName',
              value: 'id',
            },
          }}
          mode="multiple"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.organizationalManagementMenu.userRole',
              }),
            },
          ]}
        />
        <ProFormRadio.Group
          colProps={{
            md:
              modalTitle === intl.formatMessage({ id: 'systemManagement.userManagement.newUser' })
                ? 24
                : 12,
          }}
          label={intl.formatMessage({ id: 'systemManagement.userManagement.userStatus' })}
          name="status"
          initialValue={'1'}
          request={async () => {
            return await fetchDictInfo(DATABASE_TYPE_ENUM.USER_STATUS);
          }}
        />
        {modalTitle !== intl.formatMessage({ id: 'systemManagement.userManagement.newUser' }) && (
          <ProFormItem
            label={intl.formatMessage({ id: 'systemManagement.userManagement.frozenState' })}
            name="freezeStatus"
          >
            <Space style={{ width: '120px' }}>
              <span>
                {currentRow?.freeze
                  ? intl.formatMessage({ id: 'systemManagement.userManagement.frozenState' })
                  : intl.formatMessage({
                      id: 'systemManagement.organizationalManagementMenu.normal',
                    })}
              </span>
              {modalTitle !==
                intl.formatMessage({ id: 'systemManagement.generalProcedure.view' }) && (
                <a onClick={handleCancelFreeze}>
                  {intl.formatMessage({ id: 'systemManagement.generalProcedure.unfreeze' })}
                </a>
              )}
            </Space>
          </ProFormItem>
        )}
        <ProFormText
          name="email"
          label={intl.formatMessage({ id: 'systemManagement.userManagement.emailAddress' })}
          placeholder="请输入"
          rules={[
            {
              type: 'email',
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.emailFormat' }),
            },
          ]}
        />
        <ProFormTextArea
          colProps={{ md: '24' }}
          label={intl.formatMessage({ id: 'systemManagement.userManagement.remarksDescription' })}
          name="remark"
        />
      </ModalForm>
    </div>
  );
};
export default TableList;
